package com.wxb.qd.aop;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Component
@Aspect
@Slf4j
public class AopLog {

    @Around("execution(* com.wxb.qd.controller.*.*(..))")
    public Object doInterceptorForLog(ProceedingJoinPoint point) throws Throwable {
        //计时开始
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        StringBuffer requestURL = request.getRequestURL();

        //获取请求参数
        Object[] args = point.getArgs();
        String reqParam = "[" + StringUtils.join(args, ", ") + "]";
        //输出日志
        log.info("路径: {}, ip: {}, 参数: {}", requestURL, request.getRemoteHost(), reqParam);

        //执行原方法
        Object result = point.proceed();

        //计时停止
        stopWatch.stop();

        log.info("花费的时间为：{}ms",stopWatch.getTotalTimeMillis());
        log.info("执行完成");
        return result;
    }
}
